package org.tjc.net.manager.config.json;

import org.tjc.net.manager.exception.ParseConfException;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: tjc
 * @description
 * @Date Created in 15:03 2020-12-27
 */
public class NgMainModule extends NgModule {
    private CopyOnWriteArrayList<NgServerModule> serverConfs = new CopyOnWriteArrayList<>();
    private CopyOnWriteArrayList<NgLocationModule> locationConfs = new CopyOnWriteArrayList<>();
    private NgHttpModule http;

    public static ModuleSet ngSet = (ctx, conf) -> {
        NgMainModule mainModule = new NgMainModule();
        for (String key : conf.getKeys()) {
            if (!MetaNgCommand.contains(key)) {
                throw new ParseConfException("unexpect key: " + key);
            }
            MetaNgCommand subCmd = MetaNgCommand.get(key);
            if (subCmd.isModule()) {
                Configuration subConf = conf.getConfiguration(key);
                subCmd.invoke(mainModule, subConf);
            } else if (subCmd.isCmd()) {
                Object value = conf.get(key);
                subCmd.invoke(mainModule,key, value);
            }

        }
    };



    public void load(Configuration conf) {

    }

    public NgHttpModule getHttp() {
        return http;
    }

    public void setHttp(NgHttpModule http) {
        this.http = http;
    }

    public void addServerModule(NgServerModule conf) {
        serverConfs.add(conf);
    }

    public void addLocationModule(NgLocationModule conf) {
        locationConfs.add(conf);
    }

    public CopyOnWriteArrayList<NgServerModule> getServerConfs() {
        return serverConfs;
    }

    public CopyOnWriteArrayList<NgLocationModule> getLocationConfs() {
        return locationConfs;
    }

    @Override
    public void init() {
        this.serverConfs.addAll(http.getServers());
        http.getServers().stream().forEach(server -> {
            this.locationConfs.addAll(server.getLocations());
        });
        http.init();
    }
}
